package com.xaptul.docpreview.action;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.xaptul.docpreview.manager.DocPreviewManager;
import com.xaptul.docpreview.util.XaptulLog;
import com.xaptul.docpreview.util.abstra.Converter;
import com.xaptul.docpreview.util.converter.ConverterMap;
import com.xaptul.docpreview.util.converter.Jodconverter;
import com.xaptul.docpreview.util.converter.TextConverter;

@Controller
@RequestMapping(value = "/docpreview")
public class DocPreviewController {

	private Logger log = XaptulLog.getLogger();

	@Autowired
	private DocPreviewManager docPreviewManager;

	private TextConverter textConverter = new TextConverter();

//	private Jodconverter jodconverter = new Jodconverter();

	private ConverterMap converterMap = new ConverterMap(new Converter[] {
			textConverter });

	@RequestMapping("/{fileName}/index.html")
	public String previewDoc(@PathVariable String fileName, HttpServletRequest request, Model model) {
		Converter converter = converterMap.getByFilename(fileName);
		if (converter == null) {
			return "redirect:/error.html";
		}
		String documentStorePath = request.getSession().getServletContext()
				.getRealPath("tmp")
				+ File.separator;
		long t = System.currentTimeMillis();
		File sourceFile = new File(documentStorePath + fileName);
		String destFileName = FilenameUtils.getBaseName(fileName)
				+ FilenameUtils.getExtension(fileName) + ".htm";
		File destFile = new File(documentStorePath + destFileName);
		converter.convert(sourceFile, destFile);
		log.info("convert complete {} {} {}ms", new Object[] { fileName, sourceFile.length(),System.currentTimeMillis() - t});
		return "redirect:/tmp/" + destFileName;
	}
	
	/** 这个方法没有任何作用 只是在页面展现可看的文件
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/index.html")
	public String index(HttpServletRequest request,Model model) {
		String documentStorePath = request.getSession().getServletContext()
		.getRealPath("tmp")
		+ File.separator;
		File tmp = new File(documentStorePath);
		File[] files = tmp.listFiles();
		List<String> txtFileList = new ArrayList<String>(); 
		for(File file : files){
			String fileName = file.getName();
			if(fileName.endsWith(".txt")){
				txtFileList.add(fileName);
			}
		}
		model.addAttribute("txtFileList", txtFileList);
		return "upload/index";
	}
}
